package com.ld.poetry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ld.poetry.config.PoetryResult;
import com.ld.poetry.dao.MusicMapper;
import com.ld.poetry.entity.Music;
import com.ld.poetry.service.MusicService;
import com.ld.poetry.vo.MusicVo;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music> implements MusicService {
    @Override
    public PoetryResult<Page> listMusic(MusicVo musicVo) {
        LambdaQueryWrapper<Music> lambdaQuery = new LambdaQueryWrapper<>();

        // 如果存在歌手名称
        if (musicVo.getArtist() != null) {
            lambdaQuery.like(Music::getArtist, musicVo.getArtist());
        }
        // 如果存在歌曲名称
        if (musicVo.getName() != null) {
            lambdaQuery.like(Music::getName, musicVo.getName());
        }
        // 如果存在歌手类型
        if (musicVo.getArtistType() != null) {
            lambdaQuery.eq(Music::getArtistType, musicVo.getArtistType());
        }

        // 分页查询
        Page<Music> page = new Page<>(musicVo.getCurrent(), musicVo.getSize());
        Page<Music> resultPage = baseMapper.selectPage(page, lambdaQuery);

        return PoetryResult.success(resultPage);
    }


    @Override
    public PoetryResult deleteMusic(Integer id) {
        Music music = baseMapper.selectById(id);
        if (music != null) {
            // 判断是否存储文件中是否有该歌曲
            String filePath = music.getFilePath();
            // 删除文件
            try {
                Path path = Paths.get(filePath);
                Files.delete(path);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            baseMapper.deleteById(id);
            return PoetryResult.success();
        } else {
            return PoetryResult.fail("歌曲不存在");
        }
    }

    @Override
    public PoetryResult selectMusic(MusicVo musicVo) {

        LambdaQueryWrapper<Music> lambdaQuery = new LambdaQueryWrapper<>();

        // 如果存在歌手名称
        if (musicVo.getArtist() != null) {
            lambdaQuery.like(Music::getArtist, musicVo.getArtist());
        }
        // 如果存在歌曲名称
        if (musicVo.getName() != null) {
            lambdaQuery.like(Music::getName, musicVo.getName());
        }
        // 如果存在歌手类型
        if (musicVo.getArtistType() != null) {
            lambdaQuery.eq(Music::getArtistType, musicVo.getArtistType());
        }
        // 查询所有符合条件的记录
        List<Music> musicList = baseMapper.selectList(lambdaQuery);

        return PoetryResult.success(musicList);
    }
}
